package sf_errors

import (
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize"
	"golang.org/x/exp/maps"
	"lib/directory"
	"os"
	"slices"
)

func fileExists(filename string) bool {
	_, err := os.Open(filename)
	if os.IsNotExist(err) {
		return false
	}
	return true
}

// 错误码生成Excel文件
func CreateErrorFile() (string, error) {
	basepath, err := os.Getwd()
	if err != nil {
		return "", err
	}
	dirPath := fmt.Sprintf("%s/export", basepath)
	exist, err := directory.PathExists(dirPath, true)
	if err != nil {
		return "", err
	}

	if !exist {
		return "", fmt.Errorf("[%s]dir not exist", dirPath)
	}

	fname := fmt.Sprintf("%s/错误码.xlsx", dirPath)
	if fileExists(fname) {
		err := os.Remove(fname)
		if err != nil {
			return "", err
		}
	}

	// 创建一个新的Excel文件并添加数据
	f := excelize.NewFile()
	// 创建一个新的工作表
	sheet := "错误码"
	index := f.NewSheet(sheet)
	// 设置工作表的活动状态
	f.SetActiveSheet(index)

	// 设置表头
	f.SetCellValue(sheet, "A1", "错误编号")
	f.SetColWidth(sheet, "A", "A", 15)

	f.SetCellValue(sheet, "B1", "错误代码")
	f.SetColWidth(sheet, "B", "B", 60)

	f.SetCellValue(sheet, "C1", "错误详情-中-简体")
	f.SetColWidth(sheet, "C", "C", 70)

	f.SetCellValue(sheet, "D1", "错误详情-中-繁体")
	f.SetColWidth(sheet, "D", "D", 70)

	f.SetCellValue(sheet, "E1", "错误详情-英")
	f.SetColWidth(sheet, "E", "E", 80)

	bodyRowIndex := 2
	errorCodes := maps.Keys(errorMessageMap)
	slices.Sort(errorCodes)
	for _, errorCode := range errorCodes {
		if codeStr, ok := errorMessageMap[errorCode]; !ok {
			f.SetCellValue(sheet, fmt.Sprintf("A%d", bodyRowIndex), errorCode)
			bodyRowIndex++
			continue
		} else {
			f.SetCellValue(sheet, fmt.Sprintf("B%d", bodyRowIndex), codeStr)
			if message, ok2 := messageMap[codeStr]; ok2 {
				f.SetCellValue(sheet, fmt.Sprintf("C%d", bodyRowIndex), message.cn)
				f.SetCellValue(sheet, fmt.Sprintf("D%d", bodyRowIndex), message.tw)
				f.SetCellValue(sheet, fmt.Sprintf("E%d", bodyRowIndex), message.en)
			}
			bodyRowIndex++
		}
	}
	// 保存Excel文件
	if err := f.SaveAs(fname); err != nil {
		return "", err
	}
	return fname, nil
}
